﻿using System;
using GalaSoft.MvvmLight;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using JmShared;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.User;
using NLog;

namespace JiveMessenger.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class ViewModelRenameGroup : ViewModelBase
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private string _nextButtonText;
        private IClient _currentClient;
        BackgroundWorker _queryServerWorker;
        public RelayCommand RenameGroupCommand { get; set; }
        public string CurrentGroupName { get; set; }
        public string GroupID { get; set; }

        private bool _success;
        public bool Success
        {
            get { return _success; }
            set
            {
                if (_success != value)
                {
                    Set(() => Success, ref _success, value);
                }
            }
        }

        private string _inputText;
        public string InputText
        {
            get { return _inputText; }
            set
            {
                if (_inputText != value)
                {
                    Set(() => InputText, ref _inputText, value);
                }
            }
        }

        private string _statusText;
        public string StatusText
        {
            get { return _statusText; }
            set
            {
                if (_statusText != value)
                {
                    Set(() => StatusText, ref _statusText, value);
                }
            }
        }

        public string NextButtonText
        {
            get { return _nextButtonText; }
            set
            {
                if (_nextButtonText != value)
                {
                    Set(() => NextButtonText, ref _nextButtonText, value);
                }
            }
        }

        private bool _isInputTextboxEnabled;
        public bool IsInputTextboxEnabled
        {
            get { return _isInputTextboxEnabled; }
            set
            {
                if (_isInputTextboxEnabled != value)
                {
                    Set(() => IsInputTextboxEnabled, ref _isInputTextboxEnabled, value);
                }
            }
        }

        private bool _isNextButtonEnabled;
        public bool IsNextButtonEnabled
        {
            get { return _isNextButtonEnabled; }
            set
            {
                if (_isNextButtonEnabled != value)
                {
                    Set(() => IsNextButtonEnabled, ref _isNextButtonEnabled, value);
                }
            }
        }

        private bool _isCancelButtonEnabled;
        public bool IsCancelButtonEnabled
        {
            get { return _isCancelButtonEnabled; }
            set
            {
                if (_isCancelButtonEnabled != value)
                {
                    Set(() => IsCancelButtonEnabled, ref _isCancelButtonEnabled, value);
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the ViewModelAddGroup class.
        /// </summary>
        public ViewModelRenameGroup(IClient currentClient, string groupID, string currentGroupName)
        {
            _currentClient = currentClient;
            this.CurrentGroupName = currentGroupName;
            this.GroupID = groupID;
            IsCancelButtonEnabled = true;
            NextButtonText = "Next";
            IsInputTextboxEnabled = true;
            IsNextButtonEnabled = true;
            _queryServerWorker = new BackgroundWorker();
            _queryServerWorker.DoWork += _queryServerWorker_DoWork;
            _queryServerWorker.RunWorkerCompleted += _queryServerWorker_RunWorkerCompleted;
            RenameGroupCommand = new RelayCommand(RenameGroupCommandAction, () => !String.IsNullOrEmpty(InputText));
        }
        public override void Cleanup()
        {
            SimpleIoc.Default.Unregister<ViewModelAddGroup>(VmHelper.Locator.ViewModelAddGroupKey);
            VmHelper.Locator.ViewModelAddGroupKey = System.Guid.NewGuid().ToString();
            _queryServerWorker.DoWork -= _queryServerWorker_DoWork;
            _queryServerWorker.RunWorkerCompleted -= _queryServerWorker_RunWorkerCompleted;
            base.Cleanup();
        }
        private void RenameGroupCommandAction()
        {
            if (this.Success)
            {
                Messenger.Default.Send(new NotificationMessage(this, "CloseWindow"));
                return;
            }
            ChatMessage msg = new ChatMessage(_currentClient.CurrentUserInfo.ID,_currentClient.CurrentUserInfo.UserName, MessageType.RenameGroup, this.InputText,this.GroupID);

            IsNextButtonEnabled = false;
            IsInputTextboxEnabled = false;
            StatusText = string.Empty;
            _queryServerWorker.RunWorkerAsync(msg);
        }

        private void _queryServerWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DatabaseQueryResponse result = (DatabaseQueryResponse)e.Result;
            if (result.Success == true)
            {
                Success = true;
                this.StatusText = string.Format("Group {0} renamed!", result.StatusText);
                NextButtonText = "Done";
                IsCancelButtonEnabled = false;
                Logger.Info("Group {0} successfully renamed", result.StatusText);
            }
            else
            {
                Success = false;
                this.StatusText = result.StatusText;
                IsInputTextboxEnabled = true;
                Logger.Warn("Rename of group failed: {0}", result.StatusText);
            }

            IsNextButtonEnabled = true;
        }

        private void _queryServerWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = _currentClient.Connection.SendRenameGroupRequest((ChatMessage)e.Argument);
        }
    }
}